package com.lge.qcontact;


import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lge.qcontact.configuration.ConfigurationActivity;
import com.lge.qcontact.threads.SyncronizeContactsThread;
import com.lge.qcontact.utils.LocalDBHelper;
import com.lge.qcontact.utils.MUtils;

/**
 * 
 * @author project
 * 로컬 db에서 그룹 list를 읽어와서 listview에 출력
 * 각 item을 클릭 시 group명을 넘겨주어 ContactListActivity를 띄워줌.
 * ListView의 각 Item 칸에 표시될 custom layout은 xml파일로 따로 작성한다. 
 */
@SuppressLint("HandlerLeak")
public class GroupListActivity extends Activity {

	private TextView textView;
	private ListView listView;
	static ArrayList<String> list ;  //= new ArrayList<String>();
	
	private GroupThread gThread;
	private String uId = null;
	IconAdapter mAdapter;
	
	
	
	
	private Handler mHandler = new Handler() {
	
		
		@Override
		public void handleMessage(Message msg) {
			Bundle result = msg.getData();
			MUtils.log("JY","[In Handler] before add | " + result.getString("groupName"));
			//list.add(result.getString("groupName"));
			MUtils.log("JY","[In Handler] after add | " + list.size());
			mAdapter.notifyDataSetChanged();
		}
	};


	


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_group_list);	
		
		Intent intent = getIntent();
		uId = intent.getExtras().get("uid").toString();

		Toast.makeText(this, "uid = "+uId +" 로 로그인 되었습니다.", Toast.LENGTH_SHORT).show();
		
		//ddddd

		
		
		list = new ArrayList<String>();
		
		
		gThread = new GroupThread(mHandler);
		gThread.setDaemon(true);
		gThread.start();
			
		
		listView = (ListView)findViewById(R.id.listView);
		mAdapter = new IconAdapter(this);
		listView.setAdapter(mAdapter);
		
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> listview, View view, int position, long id) {
				// TODO Auto-generated method stub
				//각 아이템을 클릭했을때 처리 해줌
				Intent intent = new Intent(GroupListActivity.this, com.lge.qcontact.ContactListActivity.class);
				intent.putExtra("groupName", list.get(position));//group Name을 전달해줘야 함. ContactListActivity에서는 getStringExtra메소드로 받는다.
				intent.putExtra("uid", uId);
				startActivity(intent);		
			}					
		});
	}
	
	class IconAdapter extends BaseAdapter {
		
		private Activity mContext;
		
		public IconAdapter(Activity mContext) {
			this.mContext = mContext;			

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return GroupListActivity.list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View row = convertView;
			
			if(row == null){
				LayoutInflater inflater = mContext.getLayoutInflater();
				row = inflater.inflate(R.layout.activity_custom_row, null);
			}
			
			TextView countText = (TextView)row.findViewById(R.id.countText);
			countText.setText((position+1)+".  ");
			
			TextView label = (TextView)row.findViewById(R.id.group);
			label.setText(GroupListActivity.list.get(position));
		
			return row;
		}	
	}
	
	@Override
	protected void onDestroy() {
		try {
			gThread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}
	
	
	class GroupThread extends Thread implements Runnable {
		
		Handler mHandler;
		String tag = null;
		
		String tempId = null;
		String tempGroupName = null;
		
		
		public GroupThread(Handler handler) {
			mHandler = handler;
		}

		public void run() {

			
			SQLiteDatabase localDB = (new LocalDBHelper(getBaseContext())).getReadableDatabase();
			String sql = "select gName from CONTACTS group by gname;";
			
			Cursor c = localDB.rawQuery(sql, null);

			
			while(c.moveToNext()){
				list.add(c.getString(0));
				
				MUtils.loge("add group name list : "  + c.getString(0) + c.getCount());
				mHandler.sendEmptyMessage(0);
			}
			
			
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.activity_loggedin, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_configuration) {
			Intent intent = new Intent(GroupListActivity.this,
					ConfigurationActivity.class);
			startActivity(intent);
		}
		return true;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		list.clear();
		
		SyncronizeContactsThread t = new SyncronizeContactsThread(getBaseContext());
		t.start();
		try {
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		GroupThread t1 = new GroupThread(mHandler);
		t1.start();
		try {
			t1.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
